package com.uiotsoft.small.app.sampler.simple;

import com.uiotsoft.small.mqtt.MqttClientOld;
import lombok.extern.slf4j.Slf4j;
import org.apache.jmeter.protocol.java.sampler.AbstractJavaSamplerClient;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.threads.JMeterContextService;
import org.apache.jmeter.threads.JMeterVariables;

import java.text.MessageFormat;

@Slf4j
public class AppDisConnectSampler extends AbstractJavaSamplerClient {
    private volatile MqttClientOld clientOld;
    @Override
    public SampleResult runTest(JavaSamplerContext javaSamplerContext) {
        SampleResult results = new SampleResult();
        results.sampleStart();
        results.setDataEncoding("UTF-8");
        JMeterVariables vars = JMeterContextService.getContext().getVariables();
        clientOld = (MqttClientOld) vars.getObject("clientOld");
        if (clientOld == null) {
            results.setSuccessful(false);
            results.setResponseMessage("Connection not found.");
            results.setResponseData("Failed. Connection not found.".getBytes());
            results.setResponseCode("500");
        }else{
            vars.remove("clientOld");
            log.info(MessageFormat.format("Disconnect connection {0}.", clientOld.getMqttClient()));
            clientOld.close();
            results.setSuccessful(true);
            results.setResponseData("Successful.".getBytes());
            results.setResponseMessage(MessageFormat.format("Connection {0} disconnected.", clientOld.getMqttClient()));
            results.setResponseCodeOK();
        }
        results.sampleEnd();
        return results;
    }
}
